package com.wuercloud.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.core.RabbitManagementTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.wuercloud.dao.ExchangesDao;
import com.wuercloud.entity.ExchangesEntity;
import com.wuercloud.service.ExchangesService;

@Service("exchangesService")
public class ExchangesServiceImpl implements ExchangesService {
	private Logger logger = LoggerFactory.getLogger(ExchangesServiceImpl.class);
	@Autowired
	private ExchangesDao exchangesDao;
	@Autowired
	private RabbitManagementTemplate rabbitManagementTemplate;
	@Value("${rabbitmq-VirtualHost}")
	private String vhost;

	@Override
	public ExchangesEntity queryObject(Integer exchangesId) {
		return exchangesDao.queryObject(exchangesId);
	}

	@Override
	public List<ExchangesEntity> queryList(Map<String, Object> map) {
		return exchangesDao.queryList(map);
	}

	@Override
	public int queryTotal(Map<String, Object> map) {
		return exchangesDao.queryTotal(map);
	}

	@Override
	public void save(ExchangesEntity exchanges) {
		// 交换机类型
		Exchange exchange = null;
		if (exchanges.getExchangesType().equals("direct")) {
			exchange = new DirectExchange(exchanges.getExchangesName(), exchanges.getExDurable(),
					exchanges.getExAutodelete());

		} else if (exchanges.getExchangesType().equals("topic")) {
			exchange = new TopicExchange(exchanges.getExchangesName(), exchanges.getExDurable(),
					exchanges.getExAutodelete());

		} else {
			exchange = new FanoutExchange(exchanges.getExchangesName(), exchanges.getExDurable(),
					exchanges.getExAutodelete());

		}
		// 新增交换机
		rabbitManagementTemplate.addExchange(vhost, exchange);
		logger.info("交换机{}创建成功:{自动删除：{},持久化:{}}", exchanges.getExchangesName(), exchanges.getExAutodelete(),
				exchanges.getExDurable());

		// 将交换机信息存到数据库
		exchangesDao.save(exchanges);
	}

	@Override
	public void update(ExchangesEntity exchanges) {
		exchangesDao.update(exchanges);
	}

	@Override

	public void delete(Integer exchangesId) {
		exchangesDao.delete(exchangesId);
	}

	@Override
	public void deleteBatch(Integer[] exchangesIds) {

		// 删除rabbitMQ交换机
		Arrays.stream(exchangesIds).forEach(exchangesId -> {
			ExchangesEntity exchangesEntity = exchangesDao.queryObject(exchangesId);
			Exchange exchange = new DirectExchange(exchangesEntity.getExchangesName());
			rabbitManagementTemplate.deleteExchange(vhost, exchange);
		});

		// 删除数据库记录
		exchangesDao.deleteBatch(exchangesIds);
	}

}
